package com.beinhospital_sw21_h2_05.beinhospitalsw21h205.controller;

import cn.dev33.satoken.util.SaResult;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.Linshi;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.Patient;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.UserTable;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.service.UserService;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 控制器类，处理与用户（User）相关的HTTP请求
 */
@CrossOrigin
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册用户接口
     *
     * @param linshi 包含注册信息的临时对象
     * @return 注册结果，成功返回成功状态，失败返回错误信息
     */
    @PostMapping("/register")
    public Result register(@RequestBody Linshi linshi) {
        log.info("注册：{}", linshi);

        // 创建用户和病人对象
        UserTable user = new UserTable();
        Patient patient = new Patient();

        // 设置用户信息
        user.setUsername(linshi.getUsername());
        user.setPassword(linshi.getPassword());

        // 设置病人信息
        patient.setPatientName(linshi.getName());
        patient.setGender(linshi.getGender());
        patient.setAge(linshi.getAge());

        // 调用userService进行注册
        int flag = userService.register(user, patient);

        // 根据注册结果返回相应的响应
        if (flag == 1) {
            return Result.success();
        } else {
            return Result.error("账号已经存在");
        }
    }

    /**
     * 登陆功能
     *
     * @param user 包含登录信息的用户对象
     * @return 登录结果，成功返回SaResult，失败返回错误信息
     */
    @PostMapping("/login")
    public SaResult emailLogin(@RequestBody UserTable user) {
        // 记录登录日志
        log.info("登录：{}", user);

        // 调用用户服务进行用户名登录
        return userService.usernameLoginService(user);
    }
}
